﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HPCERP.Infrastructure.DomainBase;
using System.Transactions;
using HPCERP.Infrastructure.RepositoryFramework;

namespace HPCERP.Infrastructure
{
    public class UnitOfWork : IUnitOfWork
    {
        private Dictionary<EntityBase, IUnitOfWorkRepository> addedEntties;
        private Dictionary<EntityBase, IUnitOfWorkRepository> changedEntities;
        private Dictionary<EntityBase, IUnitOfWorkRepository> deletedEntities;

        public UnitOfWork()
        {
            this.addedEntties = new Dictionary<EntityBase, IUnitOfWorkRepository>();
            this.changedEntities = new Dictionary<EntityBase, IUnitOfWorkRepository>();
            this.deletedEntities = new Dictionary<EntityBase, IUnitOfWorkRepository>();
        }

        public void RegisterAdded(DomainBase.EntityBase entity, IUnitOfWorkRepository repository)
        {
            this.addedEntties.Add(entity, repository);
        }

        public void RegisterChanged(DomainBase.EntityBase entity, IUnitOfWorkRepository repository)
        {
            this.changedEntities.Add(entity, repository);
        }

        public void RegisterRemoved(DomainBase.EntityBase entity, IUnitOfWorkRepository repository)
        {
            this.deletedEntities.Add(entity, repository);
        }

        public void Commit()
        {
            using (TransactionScope scope = new TransactionScope())
            {
                foreach (EntityBase entity in this.deletedEntities.Keys)
                {
                    this.deletedEntities[entity].PersistDeletedItem(entity);
                }

                foreach (EntityBase entity in this.addedEntties.Keys)
                {
                    this.addedEntties[entity].PersistDeletedItem(entity);
                }

                foreach (EntityBase entity in this.changedEntities.Keys)
                {
                    this.changedEntities[entity].PersistDeletedItem(entity);
                }
                scope.Complete();
            }
            this.deletedEntities.Clear();
            this.addedEntties.Clear();
            this.changedEntities.Clear();
        }



        public void RegisterAdded(EntityBase entity, IUnitOfWork repository)
        {
            throw new NotImplementedException();
        }

        public void RegisterChanged(EntityBase entity, IUnitOfWork repository)
        {
            throw new NotImplementedException();
        }

        public void RegisterRemoved(EntityBase entity, IUnitOfWork repository)
        {
            throw new NotImplementedException();
        }
    }
}
